package com.example.administrator.about_huanxin.presenter.fragment;

import android.util.Log;

import com.example.administrator.about_huanxin.model.UserEntity;
import com.example.administrator.about_huanxin.view.fragment.HaoYouFragmentView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by Administrator on 2017/3/24 0024.
 */

public class HaoYouPresnerImp implements HaoYouPresener {

    private HaoYouFragmentView haoYouFragmentView;

    public HaoYouPresnerImp(HaoYouFragmentView haoYouFragmentView) {
        this.haoYouFragmentView = haoYouFragmentView;
    }

    @Override
    public void getFrienList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> usernames = null;
                try {
                    usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                } catch (HyphenateException e) {
                    usernames = null;
                    e.printStackTrace();
                } finally {
                    getFriendInfo(usernames);
                }
            }
        }).start();
    }


    private void getFriendOne(String str) {
        BmobQuery<UserEntity> result = new BmobQuery<>();
        result.addWhereEqualTo("username", str)
                .order("createdAt")
                .findObjects(new FindListener<UserEntity>() {
                    @Override
                    public void done(List<UserEntity> list, BmobException e) {
                        if (list != null && e == null) {
                            if (list.size() > 0) {
                                putData2List(list.get(0));
                            } else {
                            }
                        } else {
                        }
                    }
                });
    }

    private List<UserEntity> users = new ArrayList<>();

    private int size = 0;

    private void putData2List(UserEntity userEntity) {
        users.add(userEntity);
        if(size == users.size()){
            haoYouFragmentView.getFriendReturnViewList(users);
        }
    }

    private void getFriendInfo(List<String> strs) {
        size = strs.size();
        for (String str : strs) {
            getFriendOne(str);
        }
    }
}
